<script lang="ts" setup>
import type { ILoginForm } from '@/api/login'
import { useToast } from 'wot-design-uni'
import { getCodeImg, getTenantList } from '@/api/login'
import { useTokenStore } from '@/store/token'
import { tabbarList } from '@/tabbar/config'
import { isPageTabbar } from '@/tabbar/store'
import { ensureDecodeURIComponent, parseUrlToObj } from '@/utils'

definePage({
  style: {
    navigationBarTitleText: '登录',
  },
})

const toast = useToast()
const redirectUrl = ref('')

// 验证码开关
const captchaEnabled = ref(true)
const codeUrl = ref('')

// 租户列表
const tenantList = ref([])
const range = ref([])
// 用户注册开关
const register = ref(false)
// 租户开关
const tenantEnabled = ref(true)

onLoad((options) => {
  console.log('login options: ', options)
  if (options.redirect) {
    redirectUrl.value = ensureDecodeURIComponent(options.redirect)
  }
  else {
    redirectUrl.value = tabbarList[0].pagePath
  }
  console.log('redirectUrl.value: ', redirectUrl.value)
})

const tokenStore = useTokenStore()

const form = ref()

const loginForm = ref<ILoginForm>({
  tenantId: '',
  username: 'admin',
  password: 'admin123',
  code: '',
  uuid: '',
})

async function handleLogin() {
  if (loginForm.value.username === '') {
    toast.error('请输入账号')
  }
  else if (loginForm.value.password === '') {
    toast.error('请输入密码')
  }
  else if (loginForm.value.code === '' && captchaEnabled.value) {
    toast.error('请输入验证码')
  }
  else {
    toast.loading('登录中，请耐心等待...')
    await doLogin()
  }
}

async function doLogin() {
  try {
    const { valid, errors } = await form.value.validate()
    if (!valid) {
      console.log('表单验证失败:', errors)
      return
    }

    if (tokenStore.hasLogin) {
      uni.navigateBack()
      return
    }

    toast.loading('登录中，请耐心等待...')

    const result = await tokenStore.login(loginForm.value)
    console.log('LoginRes', result)
    if (result.success) {
      toast.close()
      toast.success(result.message)
      loginSuccess()
    } else {
      toast.close()
      toast.error(result.message)
      getCode() // 刷新验证码
    }
  }
  catch (error) {
    console.log('登录失败', error)
    toast.close()
    if (captchaEnabled.value) {
      getCode()
    }
  }
}

// 登录成功后，处理函数
function loginSuccess() {
  console.log('登录成功')
  let path = redirectUrl.value
  if (!path.startsWith('/')) {
    path = `/${path}`
  }
  const { path: _path, query } = parseUrlToObj(path)
  console.log('_path:', _path, 'query:', query, 'path:', path)
  console.log('isPageTabbar(_path):', isPageTabbar(_path))

  if (isPageTabbar(_path)) {
    // 经过我的测试 switchTab 不能带 query 参数, 不管是放到 url  还是放到 query ,
    // 最后跳转过去的时候都会丢失 query 信息
    uni.switchTab({
      url: path,
    })
  }
  else {
    uni.navigateBack()
  }
}

// 用户注册
function handleUserRegister() {
  // proxy.$tab.redirectTo(`/pages/register`)
}

// 隐私协议
function handlePrivacy() {
  // proxy.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
}

// 用户协议
function handleUserAgrement() {
  // proxy.$tab.navigateTo(`/pages/common/webview/index?title=${site.title}&url=${site.url}`)
}

// 获取图形验证码
function getCode() {
  getCodeImg().then((res) => {
    const { data } = res
    captchaEnabled.value = data.captchaEnabled === undefined ? true : data.captchaEnabled
    if (captchaEnabled.value) {
      codeUrl.value = `data:image/gif;base64,${data.img}`
      loginForm.value.uuid = data.uuid
    }
  })
}

// 获取租户信息
function getTenant() {
  getTenantList().then((res) => {
    const data = res.data
    tenantEnabled.value = data.tenantEnabled === undefined ? true : data.tenantEnabled
    if (tenantEnabled.value) {
      tenantList.value = data.voList
      if (tenantList.value != null && tenantList.value.length !== 0) {
        loginForm.value.tenantId = tenantList.value[0].tenantId
        // eslint-disable-next-line array-callback-return
        tenantList.value.map((row) => {
          range.value.push({
            value: row.tenantId,
            label: row.companyName,
          })
        })
      }
    }
  })
}

getCode()
getTenant()
</script>

<template>
  <view class="page">
    <view class="normal-login-container">
      <view class="logo-content align-center flex justify-center">
        <image style="width: 100rpx;height: 100rpx;" src="@/static/logo.png" mode="widthFix" />
        <text class="title">RuoYi移动端登录</text>
      </view>
      <view class="login-form-content">
        <wd-form ref="form" :model="loginForm" error-type="toast">
          <wd-cell-group border>
            <wd-picker
              v-model="loginForm.tenantId" label="企业"
              label-width="100px"
              prop="tenantId" :columns="range"
              :rules="[{ required: true, message: '请选择企业' }]"
            />
            <wd-input
              v-model="loginForm.username"
              label="账号"
              label-width="100px"
              prop="username"
              clearable
              placeholder="请输入账号"
              :rules="[{ required: true, message: '请填写账号' }]"
            />
            <wd-input
              v-model="loginForm.password"
              label="密码"
              label-width="100px"
              prop="password"
              show-password
              clearable
              placeholder="请输入密码"
              :rules="[{ required: true, message: '请填写密码' }]"
            />
            <wd-row>
              <wd-col :span="16">
                <wd-input
                  v-model="loginForm.code"
                  label="验证码"
                  label-width="100px"
                  prop="code"
                  clearable
                  placeholder="请输入验证码"
                  :rules="[{ required: true, message: '请填写验证码' }]"
                />
              </wd-col>
              <wd-col :span="8">
                <wd-img width="100%" :height="38" :src="codeUrl" @click="getCode" />
              </wd-col>
            </wd-row>
          </wd-cell-group>
          <view class="login-btn">
            <wd-button type="primary" block @click="doLogin">
              登 录
            </wd-button>
          </view>
        </wd-form>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
page {
  background-color: #ffffff;
}

.normal-login-container {
  width: 100%;

  .logo-content {
    width: 100%;
    font-size: 21px;
    text-align: center;
    padding-top: 15%;

    image {
      border-radius: 4px;
    }

    .title {
      margin-left: 10px;
    }
  }

  .login-form-content {
    text-align: center;
    margin: 20px auto;
    margin-top: 15%;
    width: 80%;

    .input-item {
      margin: 20px auto;
      height: 45px;

      .icon {
        font-size: 38rpx;
        margin-left: 10px;
        color: #999;
      }
    }

    .login-btn {
      margin-top: 20px;
      height: 45px;
    }

    .reg {
      margin-top: 15px;
    }

    .xieyi {
      color: #333;
      margin-top: 20px;
    }

    .login-code {
      height: 38px;
      float: left;

      .login-code-img {
        height: 38px;
        position: absolute;
        margin-left: 10px;
        width: 200rpx;
      }
    }
  }
}
</style>
